package com.gin.supermarket_inventory_system.commodity.service;

import com.gin.database.service.MyService;
import com.gin.supermarket_inventory_system.commodity.entity.CommodityTypePo;

import java.util.*;

/**
 *
 * @since : 2023/10/9 14:15
 * @author : ginstone
 * @version : v1.0.0
 **/
public interface CommodityTypeService extends MyService<CommodityTypePo> {
    /**
     * 返回id -> 类型全名的Map
     * @return 类型全名MAP
     */
    default HashMap<Long,String> getFullNameMap(){
        final HashMap<Long, String> map = new HashMap<>();

        final List<CommodityTypePo> list = list();
        list.forEach(item-> map.put(item.getId(),getFullName(item,list)));

        return map;
    }

    /**
     * 返回商品类型全名
     * @param item 商品类型
     * @param list 商品类型全表
     * @return 商品类型全名
     */
    static String getFullName(CommodityTypePo item, List<CommodityTypePo> list){
        List<String> res = new ArrayList<>();
        res.add(item.getName());

        while (item.getParentId() != null) {
            CommodityTypePo finalItem = item;
            final CommodityTypePo parent = list.stream().filter(i -> Objects.equals(i.getId(), finalItem.getParentId())).findFirst().orElse(null);
            if (parent!=null) {
                res.add(0,parent.getName());
                item = parent;
            }else{
                break;
            }
        }
        return String.join("/",res);
    };
}